package com.hmusic.mymusic.service.impl;

import com.hmusic.mymusic.dao.SongMapper;
import com.hmusic.mymusic.domain.Singer;
import com.hmusic.mymusic.domain.Song;
import com.hmusic.mymusic.service.SongService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * 歌曲service实现类
 */
@Service
public class SongServiceImpl implements SongService {

    @Autowired
    private SongMapper songMapper;
    @Value("${songPic.dir}")
    private String realPath;

    /**
     * 添加歌曲
     *
     * @param song
     */
    @Override
    public void insert(Song song) {
        songMapper.insert(song);
    }

    /**
     * 修改歌曲
     *
     * @param song
     */
    @Override
    public void update(Song song) {
        songMapper.update(song);
    }

    /**
     * 删除歌曲
     *
     * @param id
     */
    @Override
    public void delete(String id) {
        try{
            String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"song";
            Song song1 = songMapper.selectByPrimaryKey(id);
            String oldSongUrl = song1.getUrl();
            String newUrl = oldSongUrl.substring(6);
            File file=new File(filePath,newUrl);
            if(file.exists())file.delete();//删除歌曲地址
            Song song = songMapper.selectByPrimaryKey(id);
            String oldSongAvatorUrl = song.getPic();
            String newSongAvatorUrl = oldSongAvatorUrl.substring(13);
            if (!newSongAvatorUrl.equals("songPic.jpeg")){
                File file1=new File(realPath,newSongAvatorUrl);
                if(file1.exists())file1.delete();//删除原有图片地址
            }
            songMapper.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据主键查询整个对象
     *
     * @param id
     */
    @Override
    public Song selectByPrimaryKey(String id) {
        return songMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询所有歌曲
     */
    @Override
    public List<Song> allSong() {
        return songMapper.allSong();
    }

    /**
     * 根据歌曲名模糊查询
     *
     * @param name
     */
    @Override
    public List<Song> songOfName(String name) {
        return songMapper.songOfName(name);
    }

    /**
     * 根据歌手id查询
     *
     * @param singer_id
     */
    @Override
    public List<Song> songOfSingerId(String singer_id) {
        return songMapper.songOfSingerId(singer_id);
    }

    /**
     * 计算歌曲数量
     */
    @Override
    public int songCount() {
        return songMapper.songCount();
    }
}
